package com.TEST;/*
   Copyright (c) 2016, lovcreate.com. All rights reserved.
 */

import java.io.*;
import java.util.*;
import java.util.Map.Entry;

/**
 * Created by liuyanwen on 2016/7/29.\
 * 功能：解析txt文件，统计符号以及汉字出现字数，对其进行排序，结果保存到resault.txt中。
 */
public class TestWord {

    //通过路径读取文件到字符串中
    public String getTXT(String filePath, String encoding) {
        try {
            File file = new File(filePath);
            if (file.isFile() && file.exists()) { //判断文件是否存在
                InputStreamReader read = new InputStreamReader(
                        new FileInputStream(file), encoding);//考虑到编码格式
                BufferedReader bufferedReader = new BufferedReader(read);
                String lineTxt = null;//用于存储文件一行内的信息
                String source = null;//用于把每行信息写入其中
                long start = System.currentTimeMillis();//当前时间
//                StringBuilder stringBuilder = new StringBuilder();
                StringBuffer stringBuffer = new StringBuffer();
                while ((lineTxt = bufferedReader.readLine()) != null) {
                    stringBuffer.append(lineTxt);
                }
                source = stringBuffer.toString();
                System.out.println(System.currentTimeMillis() - start);//中间代码运行时间
                read.close();
                Map<Character, Integer> oldmap = pross(source);
                Map<Character, Integer> newmap = sortMap(oldmap);
                String filestr=formatStr(newmap);
                toResault(filestr);
                return source;
            } else {
                System.out.println("找不到指定的文件");
                return null;
            }
        } catch (Exception e) {
            System.out.println("读取文件内容出错");
            e.printStackTrace();
            return null;
        }
    }

    // 统计数字或者字符出现的次数，并封装到map中
    public TreeMap<Character, Integer> pross(String str) {
        char[] charArray = str.toCharArray();//把字符串封装进字符数组
        TreeMap<Character, Integer> tm = new TreeMap<Character, Integer>();
        for (int x = 0; x < charArray.length; x++) {
            if (!tm.containsKey(charArray[x])) {
                tm.put(charArray[x], 1);//map中没有该字符设置value为1
            } else {
                int count = tm.get(charArray[x]) + 1;//map中有该字符value+1
                tm.put(charArray[x], count);
            }
        }
        return tm;
    }

    //排序map
    public Map sortMap(Map oldMap) {
        ArrayList<Entry<Character, Integer>> list = new ArrayList<Entry<Character, Integer>>(oldMap.entrySet());//把map存到arraylist内进行排序
        Collections.sort(list, new Comparator<Entry<Character, Integer>>() {
            //@Override
            public int compare(Entry<Character, Integer> arg0, Entry<Character, Integer> arg1) {//重写compare方法
                return arg1.getValue() - arg0.getValue();//0-1升序，1-0为降序
            }
        });
        Map newMap = new LinkedHashMap();
        for (int i = 0; i < list.size(); i++) {//把数据写入map中
            newMap.put(list.get(i).getKey(), list.get(i).getValue());
        }
        return newMap;
    }

    //把map转换成String
    public String formatStr(Map<Character, Integer> map) {
        String str = null;
        Entry entry;
        StringBuffer sb = new StringBuffer();
        sb.append("┃");
        for (Iterator iterator = map.entrySet().iterator(); iterator.hasNext(); )//遍历map
        {
            entry = (Entry) iterator.next();
            sb.append(entry.getKey().toString()).append(":").append(null == entry.getValue() ? "" :
                    entry.getValue().toString()).append(iterator.hasNext() ? "\n┃" : "");//把k和v按格式添加到sb中
        }
        str = sb.toString();
        return str;

    }

    //将排序结果写到resault.txt文件中
    public void toResault(String resault) {

        FileWriter fw = null;
        try {
//            File file=new File("");
            fw = new FileWriter("resault.txt");
            fw.write(resault);//无法实现追加可写，存在覆盖现象
            fw.close();
        } catch (IOException e1) {
            e1.printStackTrace();
            System.out.println("文件写入错误");
            System.exit(-1);
        }
    }

    public static void main(String args[]) throws IOException{
        long start = System.currentTimeMillis();//开始时间
        TestWord tw = new TestWord();
        System.out.println("开始解析");
        File file=new File("");
        String path=file.getCanonicalPath();

        String newfile = tw.getTXT(path+"\\SDYXZ.txt", "UTF-8");//测试

        System.out.println("解析结束");
        System.out.println(System.currentTimeMillis() - start);//程序运行总时间
    }
}